<?php
  require('includes/application_top.php');
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">
<div id="spiffycalendar" class="text"></div>
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
    </table></td>
<!-- body_text //-->
    <td width="100%" valign="top">
    <table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading">Tìm kiếm sản phẩm</td>
            <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
          </tr>
        </table></td>
      </tr>  
      <tr>
        <td>
            <form name="orders_product_search" action="orders_product_search.php" method="get">
            <?php
                //echo tep_draw_form('orders_product_search', 'orders_product_search.php?action=process');
                echo tep_hide_session_id();
                echo tep_draw_hidden_field('action', 'process');                
            ?>
            <table border="0" width="100%" cellspacing="0" cellpadding="0">
              <tr>
                <td>
                    <?php 
                        echo tep_draw_input_field('keywords', '', 'style="width: 340px"');
                        echo tep_draw_checkbox_field('search_in_description', '1') . ' ' . 'Tìm trong mô tả sản phẩm';
                    ?>
                    <?php echo tep_image_submit('button_search.gif', 'Tìm kiếm'); ?>
                </td>
              </tr>
              <?php 
                function tep_get_categories($categories_array = '', $parent_id = '0', $indent = '') {
                    global $languages_id;
                
                    if (!is_array($categories_array)) $categories_array = array();
                
                    $categories_query = tep_db_query("select c.categories_id, cd.categories_name from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where parent_id = '" . (int)$parent_id . "' and c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by sort_order, cd.categories_name");
                    while ($categories = tep_db_fetch_array($categories_query)) {
                      $categories_array[] = array('id' => $categories['categories_id'],
                                                  'text' => $indent . $categories['categories_name']);
                
                      if ($categories['categories_id'] != $parent_id) {
                        $categories_array = tep_get_categories($categories_array, $categories['categories_id'], $indent . '&nbsp;&nbsp;');
                      }
                    }
                
                    return $categories_array;
                  }
                  
                  function tep_get_subcategories(&$subcategories_array, $parent_id = 0) {
                    $subcategories_query = tep_db_query("select categories_id from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$parent_id . "'");
                    while ($subcategories = tep_db_fetch_array($subcategories_query)) {
                      $subcategories_array[sizeof($subcategories_array)] = $subcategories['categories_id'];
                      if ($subcategories['categories_id'] != $parent_id) {
                        tep_get_subcategories($subcategories_array, $subcategories['categories_id']);
                      }
                    }
                  }
                
                  function tep_get_manufacturers($manufacturers_array = '') {
                    if (!is_array($manufacturers_array)) $manufacturers_array = array();
                
                    $manufacturers_query = tep_db_query("select manufacturers_id, manufacturers_name from " . TABLE_MANUFACTURERS . " order by manufacturers_name");
                    while ($manufacturers = tep_db_fetch_array($manufacturers_query)) {
                      $manufacturers_array[] = array('id' => $manufacturers['manufacturers_id'], 'text' => $manufacturers['manufacturers_name']);
                    }
                
                    return $manufacturers_array;
                  }
                  
                  // Parse search string into indivual objects
                  function tep_parse_search_string($search_str = '', &$objects) {
                    $search_str = trim(strtolower($search_str));
                
                // Break up $search_str on whitespace; quoted string will be reconstructed later
                    $pieces = split('[[:space:]]+', $search_str);
                    $objects = array();
                    $tmpstring = '';
                    $flag = '';
                
                    for ($k=0; $k<count($pieces); $k++) {
                      while (substr($pieces[$k], 0, 1) == '(') {
                        $objects[] = '(';
                        if (strlen($pieces[$k]) > 1) {
                          $pieces[$k] = substr($pieces[$k], 1);
                        } else {
                          $pieces[$k] = '';
                        }
                      }
                
                      $post_objects = array();
                
                      while (substr($pieces[$k], -1) == ')')  {
                        $post_objects[] = ')';
                        if (strlen($pieces[$k]) > 1) {
                          $pieces[$k] = substr($pieces[$k], 0, -1);
                        } else {
                          $pieces[$k] = '';
                        }
                      }
                
                // Check individual words
                
                      if ( (substr($pieces[$k], -1) != '"') && (substr($pieces[$k], 0, 1) != '"') ) {
                        $objects[] = trim($pieces[$k]);
                
                        for ($j=0; $j<count($post_objects); $j++) {
                          $objects[] = $post_objects[$j];
                        }
                      } else {
                /* This means that the $piece is either the beginning or the end of a string.
                   So, we'll slurp up the $pieces and stick them together until we get to the
                   end of the string or run out of pieces.
                */
                
                // Add this word to the $tmpstring, starting the $tmpstring
                        $tmpstring = trim(ereg_replace('"', ' ', $pieces[$k]));
                
                // Check for one possible exception to the rule. That there is a single quoted word.
                        if (substr($pieces[$k], -1 ) == '"') {
                // Turn the flag off for future iterations
                          $flag = 'off';
                
                          $objects[] = trim($pieces[$k]);
                
                          for ($j=0; $j<count($post_objects); $j++) {
                            $objects[] = $post_objects[$j];
                          }
                
                          unset($tmpstring);
                
                // Stop looking for the end of the string and move onto the next word.
                          continue;
                        }
                
                // Otherwise, turn on the flag to indicate no quotes have been found attached to this word in the string.
                        $flag = 'on';
                
                // Move on to the next word
                        $k++;
                
                // Keep reading until the end of the string as long as the $flag is on
                
                        while ( ($flag == 'on') && ($k < count($pieces)) ) {
                          while (substr($pieces[$k], -1) == ')') {
                            $post_objects[] = ')';
                            if (strlen($pieces[$k]) > 1) {
                              $pieces[$k] = substr($pieces[$k], 0, -1);
                            } else {
                              $pieces[$k] = '';
                            }
                          }
                
                // If the word doesn't end in double quotes, append it to the $tmpstring.
                          if (substr($pieces[$k], -1) != '"') {
                // Tack this word onto the current string entity
                            $tmpstring .= ' ' . $pieces[$k];
                
                // Move on to the next word
                            $k++;
                            continue;
                          } else {
                /* If the $piece ends in double quotes, strip the double quotes, tack the
                   $piece onto the tail of the string, push the $tmpstring onto the $haves,
                   kill the $tmpstring, turn the $flag "off", and return.
                */
                            $tmpstring .= ' ' . trim(ereg_replace('"', ' ', $pieces[$k]));
                
                // Push the $tmpstring onto the array of stuff to search for
                            $objects[] = trim($tmpstring);
                
                            for ($j=0; $j<count($post_objects); $j++) {
                              $objects[] = $post_objects[$j];
                            }
                
                            unset($tmpstring);
                
                // Turn off the flag to exit the loop
                            $flag = 'off';
                          }
                        }
                      }
                    }
                
                // add default logical operators if needed
                    $temp = array();
                    for($i=0; $i<(count($objects)-1); $i++) {
                      $temp[] = $objects[$i];
                      if ( ($objects[$i] != 'and') &&
                           ($objects[$i] != 'or') &&
                           ($objects[$i] != '(') &&
                           ($objects[$i+1] != 'and') &&
                           ($objects[$i+1] != 'or') &&
                           ($objects[$i+1] != ')') ) {
                        $temp[] = ADVANCED_SEARCH_DEFAULT_OPERATOR;
                      }
                    }
                    $temp[] = $objects[$i];
                    $objects = $temp;
                
                    $keyword_count = 0;
                    $operator_count = 0;
                    $balance = 0;
                    for($i=0; $i<count($objects); $i++) {
                      if ($objects[$i] == '(') $balance --;
                      if ($objects[$i] == ')') $balance ++;
                      if ( ($objects[$i] == 'and') || ($objects[$i] == 'or') ) {
                        $operator_count ++;
                      } elseif ( ($objects[$i]) && ($objects[$i] != '(') && ($objects[$i] != ')') ) {
                        $keyword_count ++;
                      }
                    }
                
                    if ( ($operator_count < $keyword_count) && ($balance == 0) ) {
                      return true;
                    } else {
                      return false;
                    }
                  }
              ?>
              <tr>
                <td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox">
                  <tr class="infoBoxContents">
                    <td><table border="0" width="100%" cellspacing="0" cellpadding="2">
                      <tr>
                        <td class="fieldKey">Danh mục</td>
                        <td class="fieldValue"><?php echo tep_draw_pull_down_menu('categories_id', tep_get_categories(array(array('id' => '', 'text' => 'Tất cả danh mục')))); ?></td>
                      </tr>
                      <tr>
                        <td class="fieldKey">&nbsp;</td>
                        <td class="smallText"><?php echo tep_draw_checkbox_field('inc_subcat', '1', true) . ' ' . 'Danh mục con'; ?></td>
                      </tr>
                      <tr>
                        <td class="fieldKey">Xuất xứ</td>
                        <td class="fieldValue"><?php echo tep_draw_pull_down_menu('manufacturers_id', tep_get_manufacturers(array(array('id' => '', 'text' => 'Tất cả xuất xứ')))); ?></td>
                      </tr>
                      <tr>
                        <td class="fieldKey" valign="top"><br />Thuộc tính sản phẩm</td>
                        <td><br />
                        <table>
                            <?php
                                  $products_options_name_query = tep_db_query("select distinct popt.products_options_id, popt.products_options_name from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "' order by popt.products_options_name");
                                  while ($products_options_name = tep_db_fetch_array($products_options_name_query)) {
                                    $products_options_array = array();
                                    $products_options_array[] = array('id' => "", 'text' => "Tất cả");
                                    $products_options_query = tep_db_query("select pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.options_id = '" . (int)$products_options_name['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . (int)$languages_id . "'");
                                    while ($products_options = tep_db_fetch_array($products_options_query)) {                                      
                                      $products_options_array[] = array('id' => $products_options['products_options_values_id'], 'text' => $products_options['products_options_values_name']);
                                    }
                            ?>                                    
                                <tr><td style="font-size: 13px;"><?php echo $products_options_name['products_options_name'] . ': '; ?></td>
                                <td><?php echo tep_draw_pull_down_menu('id[' . $products_options_name['products_options_id'] . ']', $products_options_array); ?></td></tr>
                            <?php
                                }
                            ?>
                            </table>
                        </td>
                      </tr>
                    </table></td>
                  </tr>
                </table></td>
              </tr>
            </table></form>
        </td>
      </tr>
      <?php 
      if($HTTP_GET_VARS['action']=='process'){
         
          $keywords = $HTTP_GET_VARS['keywords'];
          $search_in_description = $HTTP_GET_VARS['search_in_description'];
          $categories_id = $HTTP_GET_VARS['categories_id'];
          $inc_subcat = $HTTP_GET_VARS['inc_subcat'];
          $manufacturers_id = $HTTP_GET_VARS['manufacturers_id'];
          
          $id_options = $HTTP_GET_VARS['id'];
              
          $listing_product_select = "select p.products_id, pd.products_name, p.products_quantity, p.products_image, p.products_price, p.products_date_added, p.products_last_modified, p.products_date_available, p.products_status, p2c.categories_id";
          $listing_product_from .= " from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
          $listing_product_where .= " where p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = p2c.products_id";
                    
          if ($keywords) {
            $listing_product_where .= " and pd.products_name like '%" . tep_db_input($keywords) . "%'";
          }
          if($search_in_description == '1'){
            $listing_product_where .= " or pd.products_description like '%" . tep_db_input($keywords) . "%'";
          }
          if ($categories_id) {
            if ($inc_subcat == '1') {
              $subcategories_array = array();
              tep_get_subcategories($subcategories_array, $categories_id);
        
              $listing_product_where .= " and (p2c.categories_id = '" . (int)$categories_id . "'";
        
              for ($i=0, $n=sizeof($subcategories_array); $i<$n; $i++ ) {
                $listing_product_query .= " or p2c.categories_id = '" . (int)$subcategories_array[$i] . "'";
              }
              $listing_product_where .= ")";
            }else {
              $listing_product_where .= " and p2c.categories_id = '" . (int)$categories_id . "'";
            }    
          }
          
          $listing_product_order .= " order by pd.products_name";
          
          $listing_product_query = $listing_product_select . $listing_product_from . $listing_product_where . $listing_product_order;
          
          if($manufacturers_id){
            $listing_product_manu_select_from = "select m.manufacturers_id, p.products_id, pd.products_name, p.products_quantity, p.products_image, p.products_price, p.products_date_added, p.products_last_modified, p.products_date_available, p.products_status, p2c.categories_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_MANUFACTURERS . " m";
            $listing_product_manu_where = " and p.manufacturers_id = m.manufacturers_id and m.manufacturers_id = '" . (int)$manufacturers_id . "'";
            $listing_product_query = $listing_product_manu_select_from . $listing_product_where . $listing_product_manu_where . $listing_product_order;  
          }
          
          if($id_options){
              $key = 1;
              foreach ($id_options as $key => $val) {
                if($val){
                    $products_id_query = "select products_id from " . TABLE_PRODUCTS_ATTRIBUTES . " where options_values_id = '".$val."' and options_id = '".$key."'";
                    //echo $products_id_query;
                    $products_query = tep_db_query($products_id_query);
                    while ($products = tep_db_fetch_array($products_query)) {
                        //print_r($products);
                        $listing_product_options_select_from = "select pd.products_name, p.products_quantity, p.products_image, p.products_price, p.products_date_added, p.products_last_modified, p.products_date_available, p.products_status, p2c.categories_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
                        $listing_product_options_where = " and p.products_id = '" . (int)$products['products_id'] . "'";
                        $listing_product_query = $listing_product_options_select_from . $listing_product_where . $listing_product_options_where . $listing_product_order;
                    }    
                }
              }            
          }                
          
          $listing_split = new splitPageResults($HTTP_GET_VARS['page'], MAX_DISPLAY_SEARCH_RESULTS, $listing_product_query, $listing_query_numrows);
          $listing_sql = tep_db_query($listing_product_query);
          
          //$listing_split = new splitPageResults($HTTP_GET_VARS['page'], MAX_DISPLAY_SEARCH_RESULTS, $listing_product_query, '10');
      ?>
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
              <tr class="dataTableHeadingRow">
                <td class="dataTableHeadingContent">Hình sản phẩm</td>
                <td class="dataTableHeadingContent">Tên sản phẩm</td>
                <td class="dataTableHeadingContent">Giá</td>
                <td class="dataTableHeadingContent">Số lượng</td>
              </tr>
<?php
  while ($listing = tep_db_fetch_array($listing_sql)) {
                echo '<tr class="dataTableRow" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)"">' . "\n";
?>
                <td class="dataTableContent"><?php echo tep_image('../'.DIR_WS_IMAGES . $listing['products_image'], $listing['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) ?></td>
                <td class="dataTableContent"><?php echo $listing['products_name']; ?></td>
                <td class="dataTableContent"><?php echo $listing['products_price']; ?></td>
                <td class="dataTableContent"><?php echo $listing['products_quantity']; ?></td>
              </tr>
<?php } ?>
            </table></td>
          </tr>
          <tr>
            <td class="smallText" valign="top" align="right">
                <?php echo $listing_split->display_count($listing_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $HTTP_GET_VARS['page'], TEXT_DISPLAY_NUMBER_OF_ORDERS); ?>
                <?php echo $listing_split->display_links($listing_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $HTTP_GET_VARS['page'],tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?>
            </td>
          </tr>
        <?php //}else{ ?>
           <!-- <tr class="dataTableHeadingRow">
            <td class="dataTableContent">Không tìm thấy sản phẩm thỏa yêu cầu.</td>
           </tr> -->    
        <?php //} ?>    
        </table></td>
      </tr>
      <?php } ?>
    </table>
    </form>
    </td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
